package office.stock.security.backingbeans;

import java.io.Serializable;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import office.stock.model.User;
import office.stock.security.SessionAttributes;
import office.stock.security.services.LoginService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@ManagedBean
@SessionScoped
public class LoginBackingBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private static final transient Log log = LogFactory.getLog(LoginBackingBean.class);
    
    private String username;
    private String password;
    
    @EJB
    private LoginService loginService;
    
    @PostConstruct
    public void postConstruct() {
	log.debug("Login bean was created");
    }
    
    public String login () {
	log.info("User " + username + " is trying to login.");
	User user = loginService.getUserByCredentials(username, password);
	if (user != null) {
	    log.info("User " + username + " has entered correct credentials and will be logged in.");
	    Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
	    sessionMap.put(SessionAttributes.USER.name(), user);
	    return getRequestedPageName();
	} else {
	    log.info("User " + username + " has entered invalid credentials.");
	    return "fail";
	}
    }

    private String getRequestedPageName() {
	Map<String, Object> sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
	String pageName = "index";
	String requestedPageURL = (String) sessionMap.get(SessionAttributes.TARGET_PAGE.name());
	if (requestedPageURL != null && !requestedPageURL.isEmpty()) {
	    int pageNamePossition = requestedPageURL.lastIndexOf("/") + 1;
	    pageName = requestedPageURL.substring(pageNamePossition, pageNamePossition + ".xhtml".length() - 1);
	    sessionMap.remove(SessionAttributes.TARGET_PAGE.name());
	}
	log.debug("requested page is " + pageName);
	return pageName;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    
} 
